package com.hzvdvmc.autosale.socket.manager;

import com.hzvdvmc.autosale.util.StringUtil;

/**
 * Created by william on 2018/1/2.
 * 异或工具类
 */

public class CheckNumUtil {

    /**
     * 获取异或结果
     *
     * @param command 0x48
     * @param data    "abccom"
     * @return
     */
    public static String getCheckNum(String command, String data) {
        Integer result = Integer.valueOf(command, 16);
        //最后一位，转16进制
        for (int i = 0; i < data.length(); i++) {
            String substring = data.substring(i, i + 1);
            String hexStr = StringUtil.convertStringToHex(substring);
            Integer dataInt = Integer.valueOf(hexStr, 16);
            result = result ^ dataInt;
        }

        String s = Integer.toHexString(result);
        if (s.length() == 1) {
            s = "0" + s;
        }
        return s;
    }

    /**
     * 获取异或结果
     *
     * @param command 0x48
     * @param data    {"23","4d","7d"}
     * @return
     */
    public static String getCheckNum(String command, String[] data) {
        Integer result = Integer.valueOf(command, 16);
        //最后一位，转16进制
        for (int i = 0; i < data.length; i++) {
            String substring = data[i];
            String hexStr = StringUtil.convertStringToHex(substring);
            Integer dataInt = Integer.valueOf(hexStr, 16);
            result = result ^ dataInt;
        }

        String s = Integer.toHexString(result);
        if (s.length() == 1) {
            s = "0" + s;
        }
        return s;
    }

    /**
     * 获取异或结果
     *
     * @param command 0x48
     * @param data    16进制的 3d5c4e
     * @return
     */
    public static String getCheckNumHex(String command, String data) {
        Integer result = Integer.valueOf(command, 16);
        //最后一位，转16进制
        for (int i = 0; i < data.length(); i += 2) {
            String hexStr = data.substring(i, i + 2);
            Integer dataInt = Integer.valueOf(hexStr, 16);
            result = result ^ dataInt;
        }
        String s = Integer.toHexString(result);
        if (s.length() == 1) {
            s = "0" + s;
        }
        return s;
    }
}
